Skip to content

Conversation

@ymc9
Copy link
Member

@ymc9 ymc9 commented Nov 10, 2025

Summary by CodeRabbit

Release Notes

  • New Features

    • Added PostgreSQL custom schema support, allowing users to specify multiple schemas and set default schema configurations.
    • Introduced automatic schema attribute generation for models, with fallback to default PostgreSQL schema when not explicitly specified.
  • Bug Fixes

    • Enhanced datasource validation to ensure default schema values are properly included in the schemas array.

Copilot AI review requested due to automatic review settings November 10, 2025 17:50
@coderabbitai
Copy link

coderabbitai bot commented Nov 10, 2025

Walkthrough

The pull request implements PostgreSQL custom schema support by adding validation for defaultSchema fields in datasources, filtering the field from Prisma output, auto-generating @@Schema attributes when needed, and introducing helper utilities for schema field access. New end-to-end tests verify validation and SQL generation behavior.

Changes

Cohort / File(s) Summary
Datasource Validation
packages/language/src/validators/datasource-validator.ts
Adds defaultSchema validation: ensures provider is postgres, extracts string literal value, and verifies the schema is included in the schemas array; emits errors if validation fails.
Prisma Schema Generation
packages/sdk/src/prisma/prisma-schema-generator.ts
Filters defaultSchema from datasource output; introduces NON_PRISMA_DATASOURCE_FIELDS constant and helper functions (getDatasourceField, datasourceHasSchemasSetting, getDefaultPostgresSchemaName); auto-adds @@Schema attributes; imports public getStringLiteral utility.
End-to-End Tests
tests/e2e/orm/client-api/pg-custom-schema.test.ts
Adds two new test cases: validating that defaultSchema must be in schemas array, and verifying per-model @@Schema scoping with correct SQL generation.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • packages/language/src/validators/datasource-validator.ts: Cross-field validation logic requires careful review to ensure error conditions are correctly identified and reported.
  • packages/sdk/src/prisma/prisma-schema-generator.ts: Multiple new helper functions and schema attribute auto-generation logic introduce moderate complexity; verify that filtering and default schema derivation work correctly across edge cases.
  • Integration between validator and generator: Ensure validation assumptions align with generation behavior.

Possibly related PRs

Poem

🐰 Hops through schemas with delight,
defaultSchema shining bright,
Postgres dances in the dark,
Validation marks its trusty mark!
Custom realms now take their flight!

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main changes: adding stricter validation for default schema configuration and implementing proper transformation of default schema to Prisma schema syntax.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/default-schema

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@claude
Copy link

claude bot commented Nov 10, 2025

Claude finished @ymc9's task —— View job


Code Review Complete

Reviewing PR #390: "fix: stricter default schema validation and proper transformation to Prisma schema"

Todo List:

  • Read and analyze datasource-validator.ts changes
  • Review prisma-schema-generator.ts modifications
  • Examine test coverage in pg-custom-schema.test.ts
  • Provide feedback on code quality and best practices
  • Check for potential bugs and security concerns
  • Evaluate performance considerations

Overall Assessment: ✅ Strong Implementation

This PR implements stricter validation for PostgreSQL schema configurations and ensures proper transformation to Prisma schema. The changes are well-structured and address important validation gaps.

Key Improvements

🔧 Enhanced Schema Validation (datasource-validator.ts:41-82)

  • Cross-field validation: Now validates that defaultSchema is included in the schemas array
  • Provider-specific constraints: Properly restricts defaultSchema and schemas to PostgreSQL only
  • Type safety: Ensures all schema values are string literals

🔄 Automatic Schema Generation (prisma-schema-generator.ts:193-204)

  • Default schema injection: Automatically adds @@schema("public") when schemas is configured but no explicit @@schema attribute exists
  • Clean field filtering: Excludes ZModel-specific defaultSchema field from Prisma schema generation

Comprehensive Test Coverage (pg-custom-schema.test.ts)

  • Edge case validation: Tests provider restrictions and cross-field validation
  • Query verification: Confirms actual SQL queries use correct schema prefixes
  • Real-world scenarios: Tests various combinations of schema configurations

Code Quality Review

Strengths

  1. Robust Validation Logic

    // packages/language/src/validators/datasource-validator.ts:73-81
    if (defaultSchemaValue && 
        !schemasValue.items.some((e) => getStringLiteral(e) === defaultSchemaValue)) {
        accept('error', `"${defaultSchemaValue}" must be included in the "schemas" array`, {
            node: schemasField,
        });
    }
    • Proper cross-field validation ensures data consistency
    • Clear, actionable error messages
  2. Smart Default Handling

    // packages/sdk/src/prisma/prisma-schema-generator.ts:225-228
    private getDefaultPostgresSchemaName(zmodel: Model) {
        const defaultSchemaField = this.getDatasourceField(zmodel, 'defaultSchema');
        return getStringLiteral(defaultSchemaField?.value) ?? 'public';
    }
    • Sensible fallback to 'public' schema
    • Clean separation of concerns with helper methods
  3. Comprehensive Error Coverage

    • Tests validate all error conditions
    • SQL query verification ensures runtime correctness

⚠️ Areas for Consideration

  1. Error Message Consistency (Minor)

    // Consider standardizing quote usage in error messages
    // Current: '"schemas" is only supported for "postgresql" provider'
    // Could be: 'The "schemas" field is only supported for PostgreSQL provider'
  2. Validation Performance (Minor)

    • Line 68: Array validation uses every() and some() which is O(n²) for large schema arrays
    • For typical use cases (< 10 schemas), this is negligible
  3. Type Safety Enhancement (Enhancement)

    // packages/sdk/src/prisma/prisma-schema-generator.ts:68
    const NON_PRISMA_DATASOURCE_FIELDS = ['defaultSchema'];
    // Consider: const NON_PRISMA_DATASOURCE_FIELDS = ['defaultSchema'] as const;

Security & Performance Analysis

🔒 Security: No Issues Found

  • All user inputs are validated as string literals
  • No SQL injection vectors (schema names are validated, not dynamic)
  • Proper input sanitization through AST parsing

Performance: Efficient Implementation

  • Validation runs at compile time, not runtime
  • Schema generation is one-time during code generation
  • Test queries confirm no performance impact on generated SQL

Test Coverage Assessment: Excellent

The test suite covers:

  • ✅ Default behavior (lines 6-68)
  • ✅ Custom schema configuration (lines 114-158)
  • ✅ Error conditions and edge cases (lines 160-214)
  • ✅ Partial schema specification (lines 216-260)
  • ✅ Both ORM and Query Builder APIs

Missing test coverage (optional enhancements):

  • Empty schemas array handling
  • Whitespace/special characters in schema names
  • Very long schema names (identifier length limits)

Recommendations

  1. Consider Adding: Input validation for schema name format (alphanumeric + underscore)
  2. Consider Adding: Warning for very long schema names that might hit database limits
  3. Low Priority: Standardize error message formatting across validators

Summary

This is a high-quality implementation that significantly improves ZenStack's PostgreSQL schema support. The code is well-structured, properly tested, and addresses real user needs without introducing technical debt or security vulnerabilities.

Verdict: ✅ Ready to merge - This PR enhances functionality while maintaining code quality standards.


Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR enhances PostgreSQL schema validation and ensures proper transformation from ZModel to Prisma schema by introducing stricter validation rules and automatic schema attribute generation.

  • Adds validation to require defaultSchema to be included in the schemas array when both are specified
  • Filters out ZModel-specific defaultSchema field when generating Prisma datasource configuration
  • Automatically adds @@schema attributes to models when schemas is defined but no explicit schema is specified

Reviewed Changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.

File Description
tests/e2e/orm/client-api/pg-custom-schema.test.ts Adds tests to verify validation of defaultSchema being included in schemas array and proper schema assignment to models without explicit @@schema attributes
packages/sdk/src/prisma/prisma-schema-generator.ts Filters out defaultSchema from datasource fields, adds automatic @@schema attribute generation for models when schemas is defined, and refactors to use centralized getStringLiteral utility
packages/language/src/validators/datasource-validator.ts Adds validation to ensure defaultSchema is a string literal and is included in the schemas array when both are specified

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/language/src/validators/datasource-validator.ts (1)

42-56: Validation logic looks good.

The defaultSchema validation correctly enforces:

  • Provider must be postgresql
  • Value must be a string literal

Consider adding validation to reject empty string values for better error messages:

 defaultSchemaValue = getStringLiteral(defaultSchemaField.value);
 if (!defaultSchemaValue) {
     accept('error', '"defaultSchema" must be a string literal', {
         node: defaultSchemaField.value,
     });
+} else if (defaultSchemaValue.trim() === '') {
+    accept('error', '"defaultSchema" cannot be an empty string', {
+        node: defaultSchemaField.value,
+    });
 }
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 267f98d and a2ad5e5.

📒 Files selected for processing (3)
  • packages/language/src/validators/datasource-validator.ts (2 hunks)
  • packages/sdk/src/prisma/prisma-schema-generator.ts (7 hunks)
  • tests/e2e/orm/client-api/pg-custom-schema.test.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (3)
tests/e2e/orm/client-api/pg-custom-schema.test.ts (1)
packages/testtools/src/client.ts (1)
  • createTestClient (53-182)
packages/language/src/validators/datasource-validator.ts (1)
packages/language/src/utils.ts (1)
  • getStringLiteral (75-77)
packages/sdk/src/prisma/prisma-schema-generator.ts (3)
packages/sdk/src/prisma/prisma-builder.ts (2)
  • SimpleField (6-6)
  • Model (115-164)
packages/language/src/utils.ts (2)
  • getAllAttributes (546-570)
  • getStringLiteral (75-77)
packages/language/src/generated/ast.ts (3)
  • Model (559-563)
  • Model (565-565)
  • isDataSource (417-419)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Agent
  • GitHub Check: build-test (20.x, sqlite)
  • GitHub Check: build-test (20.x, postgresql)
🔇 Additional comments (8)
packages/language/src/validators/datasource-validator.ts (1)

73-81: Excellent cross-field validation.

The logic correctly ensures that when both defaultSchema and schemas are present, the default schema value is included in the schemas array. Reporting the error on the schemasField node is appropriate since the fix requires updating the schemas array.

tests/e2e/orm/client-api/pg-custom-schema.test.ts (2)

197-214: Comprehensive validation test.

This test effectively verifies that the cross-field validation between defaultSchema and schemas works correctly, ensuring the default schema is included in the schemas array.


216-260: Excellent integration test.

This test validates the key functionality of the PR:

  • Models with explicit @@schema use that schema
  • Models without @@schema use the defaultSchema value
  • SQL generation correctly targets the appropriate schemas

The use of log inspection to verify SQL targeting is a robust approach.

packages/sdk/src/prisma/prisma-schema-generator.ts (5)

67-68: Clean abstraction for non-Prisma fields.

Defining NON_PRISMA_DATASOURCE_FIELDS as a constant provides a clear, maintainable way to identify fields that exist in ZModel but not in Prisma schema.


113-118: Correct filtering implementation.

The datasource field filtering correctly excludes non-Prisma fields while preserving all standard Prisma datasource configuration.


216-228: Well-designed helper utilities.

These helper methods provide clean abstractions for:

  • Accessing datasource fields
  • Checking for schemas configuration
  • Determining the default PostgreSQL schema name with appropriate fallback

The use of the imported getStringLiteral utility is the right choice.


185-187: Improved attribute handling.

Computing allAttributes once and reusing it is more efficient and enables the subsequent @@Schema existence check.


193-204: Correct auto-generation logic.

The conditional auto-generation of @@schema attributes is well-designed:

  • Only activates when the datasource declares schemas
  • Respects explicit @@schema attributes on models
  • Uses the appropriate default value from defaultSchema or falls back to 'public'

This implementation aligns perfectly with the test case "allows specifying schema only on a few models".

@ymc9 ymc9 merged commit 7a207bf into dev Nov 10, 2025
12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants